<template>
  <div class="container">
    <div class="app-container">
      <div class="addBtn">
        <el-button type="primary" size="mini" @click="showDialog=true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table v-loading="loading" border :data="data" stripe style="width:100%; margin: 15px;">
        <!-- 放置列 -->
        <el-table-column prop="id" width="50" label="序号" />
        <el-table-column prop="name" align="center" width="195" label="角色">
          <template v-slot="{row}">
            <!-- 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="195" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" active-value="已启用" inactive-value="未启用" />
            <span v-else>{{ row.state }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" style="width:290px" type="textarea" size="mini" :rows="2" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <!-- 放置操作按钮 -->
              <el-button size="mini" type="primary" @click="updateRole(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else> <el-button type="text" size="mini" @click="assignRole(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="edit(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delRole(row.id)"
              >
                <el-button slot="reference" style="margin-left: 10px;" type="text" size="mini">删除</el-button>
              </el-popconfirm></template>

          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="center" align="middle" style="height: 60px;">
        <el-pagination :page-size="pageParams.pagesize" :total="pageParams.total" layout="prev, pager, next" @current-change="handleCurrentChange" />

      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="close">
      <el-form ref="form" :rules="rules" :model="roleForm" label-width="80px" size="mini">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="roleForm.state" :active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" style="width: 300px;" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="addRole">确认</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col></el-row>
        </el-form-item>

      </el-form>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="showPermissonDialog">
      <el-tree
        ref="permissonTree"
        :default-checked-keys="permIds"
        default-expand-all
        show-checkbox
        :data="permList"
        node-key="id"
        :props="{label:'name'}"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6"><el-button size="mini" type="primary" @click="assignPerm">确定</el-button>
          <el-button size="mini" @click="showPermissonDialog=false">取消</el-button></el-col>
      </el-row>
    </el-dialog>

  </div>
</template>
<script>

import { getRoleData, addRole, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { getPermList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      data: [],
      loading: false,
      showDialog: false,
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [{
          required: true, message: '不能为空',
          trigger: 'blur'
        }],
        description: [{
          required: true, message: '不能为空',
          trigger: 'blur'
        }]
      },
      showPermissonDialog: false,
      permList: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleData()
  },
  methods: {
    async getRoleData() {
      this.loading = true
      const { total, rows } = await getRoleData(this.pageParams)
      this.pageParams.total = total
      rows.forEach(item => {
        if (item.state === 1) {
          item.state = '已启用'
        } else {
          item.state = '未启用'
        }
        // 针对每一行添加一个编辑标记
        // 数据响应式的问题 数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象,属性名称，初始值) 可以针对目标对象 添加属性 添加初始值
        this.$set(item, 'isEdit', false)
        // 初始化定义缓存数据
        this.$set(item, 'editRow', {
          state: item.state,
          name: item.name,
          description: item.description
        })
      })
      this.data = rows
      this.loading = false
    },
    // 切换分页时 请求新的数据
    handleCurrentChange(value) {
      this.pageParams.page = value // 赋值当前页码
      this.getRoleData()
    },
    close() {
      this.$refs.form.resetFields()
      this.roleForm.state = 0

      this.showDialog = false
    },
    async addRole() {
      this.$refs.form.validate(async isOk => {
        if (isOk) {
          await addRole(this.roleForm)
          this.$message.success('添加角色成功')
          this.close()
          this.getRoleData()
        }
      })
    },
    edit(row) {
      // 更新缓存数据
      row.isEdit = true
      row.editRow.state = row.state
      row.editRow.description = row.description
      row.editRow.name = row.name
    },
    async updateRole(row) {
      if (row.editRow.state === '已启用') {
        row.editRow.state = 1
      } else {
        row.editRow.state = 0
      }
      row.editRow.id = row.id
      await updateRole(row.editRow)
      this.$message.success('更新角色详情成功')
      row.isEdit = false
      this.getRoleData()
    },

    async delRole(id) {
      await delRole(id)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      if (this.data.length === 1) this.pageParams.page--
      this.getRoleData()
    },
    async assignRole(id) {
      this.currentRoleId = id
      this.permList = transListToTreeData(await getPermList(), 0)
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.showPermissonDialog = true
    },
    async assignPerm() {
      const permIds = this.$refs.permissonTree.getCheckedKeys()
      await assignPerm({
        id: this.currentRoleId,
        permIds
      })
      this.$message.success('分配角色权限成功')
      this.showPermissonDialog = false
    }

  }
}
</script>
  <style scoped>
.addBtn{
  padding: 15px;
}</style>
